//
//  MainMenuViewController.m
//  MobileSail
//
//  Created by Roy Brown on 8/8/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "MainMenuViewController.h"
#import "MobileSailAppDelegate.h"

@implementation MainMenuViewController

@synthesize tableOrderController,myLabel;


- (void)viewDidLoad {
    [super viewDidLoad];
	self.title = @"Main Menu";
	//[myLabel setText:@"x1"];
	
	//[self startTCPServer];
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

/*
 - (void)viewWillAppear:(BOOL)animated {
 [super viewWillAppear:animated];
 }
 */
/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //return 1;
	MobileSailAppDelegate *appDelegate = (MobileSailAppDelegate *)[[UIApplication sharedApplication] delegate];
	return appDelegate.items.count;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    /*
    static NSString *MyIdentifier = @"MyIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
    }
    [cell setText:@"Table Order"];
    // Set up the cell...
	*/
	static NSString *MyIdentifier = @"MyIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
    }
    
	MobileSailAppDelegate *appDelegate = (MobileSailAppDelegate *)[[UIApplication sharedApplication] delegate];
	MainMenuItems *i = (MainMenuItems *)[appDelegate.items objectAtIndex:indexPath.row];
	
    [cell setText:i.name];
	
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	if (self.tableOrderController == nil)
	{
		TableOrderController *tableorder = [[TableOrderController alloc] initWithNibName:@"TableOrder" bundle:[NSBundle mainBundle]];
		self.tableOrderController = tableorder;
		[tableorder release];
	}
	
	[self.navigationController pushViewController:self.tableOrderController animated:YES];
}

- (void) startTCPServer
{
	[_server release];
	_server = nil;
	
	[_inStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[_inStream release];
	_inStream = nil;
	_inReady = NO;
	
	[_outStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[_outStream release];
	_outStream = nil;
	_outReady = NO;
	
	_server = [TCPServer new];
	[_server setDelegate:self];
	NSError* error;
	
	if(_server == nil || ![_server start:&error]) {
		//NSLog(@"Failed creating server: %@", error);
		//[self _showAlert:@"Failed creating server"];
		[myLabel setText:@"Failed creating server"];
	} else {
		[myLabel setText:@"success"];
		//NSLog(@"yo:");
	}
}

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
    [super dealloc];
}

- (void) openStreams
{
	[myLabel setText:@"open stream"];
	_inStream.delegate = self;
	[_inStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[_inStream open];
	_outStream.delegate = self;
	[_outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[_outStream open];
}

@end

@implementation MainMenuViewController (NSStreamDelegate)

- (void) stream:(NSStream*)stream handleEvent:(NSStreamEvent)eventCode
{
	[myLabel setText:@"stream event"];
	
	switch(eventCode) {
		case NSStreamEventOpenCompleted:
		{
			[myLabel setText:@"stream event open completed"];
			//[self destroyPicker];
			
			[_server release];
			_server = nil;
			
			if (stream == _inStream)
				_inReady = YES;
			else
				_outReady = YES;
			
			if (_inReady && _outReady) {
				//alertView = [[UIAlertView alloc] initWithTitle:@"Game started!" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Continue", nil];
				//[alertView show];
				//[alertView release];
			}
			break;
		}
		case NSStreamEventHasBytesAvailable:
		{
			[myLabel setText:@"stream event bytes available"];
			if (stream == _inStream) {
				[myLabel setText:@"stream equal stream"];
				
				uint8_t b;
				unsigned int len = 0;
				len = [_inStream read:&b maxLength:sizeof(uint8_t)];
				if(!len) {
					if ([stream streamStatus] != NSStreamStatusAtEnd)
						[myLabel setText:@"Failed reading data from peer"];
						//return;
				} else {
					[myLabel setText:@"stream has length"];
					
					BOOL done = FALSE;
					NSString *cuerpo;
					UInt8 bufi[4096];
					
					//return;
					//while (!done) {
					CFIndex bytesRead = CFReadStreamRead((CFReadStreamRef)_inStream, bufi, sizeof(bufi));
					switch (bytesRead) {
						case -1:
							[myLabel setText:@"-1"];
							done=TRUE;
							break;
						case 0:
							[myLabel setText:@"0"];
							done=TRUE;
							break;
						default:
							[myLabel setText:@"1"];
							cuerpo = [NSString stringWithCString: (const char*)bufi length: bytesRead];
					}
					//}
					
					[myLabel setText:cuerpo];
					
					//[self _showAlert:cuerpo];
					
					//clean all objects created	
				}			
			}
			break;
		}
		case NSStreamEventEndEncountered:
		{
			[myLabel setText:@"stream event end"];
			/*NSArray*				array = [_window subviews];
			 TapView*				view;
			 UIAlertView*			alertView;
			 
			 NSLog(@"%s", _cmd);
			 
			 //Notify all tap views
			 for(view in array)
			 [view touchUp:YES];
			 
			 alertView = [[UIAlertView alloc] initWithTitle:@"Peer Disconnected!" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"Continue", nil];
			 [alertView show];
			 [alertView release];*/
			
			break;
		}
			
		case NSStreamEventHasSpaceAvailable:
		{
			[myLabel setText:@"stream event has space"];
			break;
		}	
		case NSStreamEventErrorOccurred:
		{
			[myLabel setText:@"stream event error"];
			break;
		}
		case NSStreamEventNone:
		{
			[myLabel setText:@"stream event none"];
			break;
		}
	}
}

@end

@implementation MainMenuViewController (TCPServerDelegate)

- (void) didAcceptConnectionForServer:(TCPServer*)server inputStream:(NSInputStream *)istr outputStream:(NSOutputStream *)ostr
{
	if (_inStream || _outStream || server != _server)
		return;
	
	[_server release];
	_server = nil;
	
	_inStream = istr;
	[_inStream retain];
	_outStream = ostr;
	[_outStream retain];
	
	[self openStreams];
}

@end